/*
 *  timer.cpp
 *  FrostOS
 *
 *  Created by bluechill on 12/10/09.
 *  Copyright 2009 SecurityOverride. All rights reserved.
 *
 */

#include <ostream.h>
#include <istream.h>
#include <irq.h>

using namespace std;

bool waiting = false;
int secondsWaiting = 0;

void setTimerPhaseUpdate(int hz)
{
    int divisor = 1193180 / hz;       /* Calculate our divisor */
    outportb(0x43, 0x36);             /* Set our command byte 0x36 */
    outportb(0x40, divisor & 0xFF);   /* Set low byte of divisor */
    outportb(0x40, divisor >> 8);     /* Set high byte of divisor */
}

/* This will keep track of how many ticks that the system
 *  has been running for */
int timer_ticks = 0;

/* Handles the timer. In this case, it's very simple: We
 *  increment the 'timer_ticks' variable every time the
 *  timer fires. By default, the timer fires 18.222 times
 *  per second. Why 18.222Hz? Some engineer at IBM must've
 *  been smoking something funky */
void timer_handler(struct regs *)
{
    /* Increment our 'tick count' */
    timer_ticks++;
	
    /* Every 18 clocks (approximately 1 second), we will
	 *  display a message on the screen */
    if (timer_ticks % 18 == 0)
    {
		if (waiting == true)
		{
			secondsWaiting++;
		}
    }
}

/* Sets up the system clock by installing the timer handler
 *  into IRQ0 */
void timer_install()
{
    /* Installs 'timer_handler' to IRQ0 */
    irq_install_handler(0, timer_handler);
}

/* This will continuously loop until the given time has
 *  been reached */
void timer_wait(int ticks)
{
    long eticks;
	
    eticks = timer_ticks + ticks;
    while(timer_ticks < eticks);
}

void timer_wait_seconds(int seconds)
{
	waiting = true;
	secondsWaiting = 0;
	while (secondsWaiting != seconds)
	{}
	waiting = false;
	secondsWaiting = 0;
}
